<template>
  <div class="dict-segmented" :style="{ width }">
    <el-segmented
      v-model="selectOptions"
      size="large"
      :options="data"
      block
    ></el-segmented>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch } from "vue"
import { getDictApi } from "@/api/dicts"
import _ from "lodash"

defineOptions({
  name: "dictSegmented",
})

const emit = defineEmits(["update:modelValue", "change"])
const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: "",
  },
  type: {
    //字典的type
    type: String,
    default: "",
  },
  isNumber: {
    type: Boolean,
    default: false,
  },
  allowEmpty: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Array,
    default: () => [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  width: {
    type: String,
    default: "600px",
  },
})

interface DataItem {
  value: string
  label: string
}

const data = ref([] as DataItem[])
const selectOptions = computed({
  get() {
    return String(props.modelValue === null ? "" : props.modelValue)
  },
  set(val) {
    const modelValue = props.modelValue as any
    emit(
      "change",
      val,
      data.value.find((item) => item?.value === selectOptions.value),
    )
    emit(
      "update:modelValue",
      typeof modelValue === "number" || props.isNumber ? Number(val) : val,
    )
  },
})

watch(
  () => props.data,
  (val: any) => {
    const _val = _.cloneDeep(val || [])
    _val.map((item: any) => {
      item.value = String(item.value)
    })
    if (props.allowEmpty && _val) {
      _val.unshift({ value: "0", label: "不限" })
    }
    data.value = _val as DataItem[]
  },
  {
    immediate: true,
    deep: true,
  },
)

onMounted(async () => {
  if (props.type) {
    const res: any = await getDictApi(props.type)
    if (res.success) {
      const val: DataItem[] = res.data || []
      val.map((item: any) => {
        item.value = String(item.value)
      })
      if (props.allowEmpty) {
        val.unshift({ value: "0", label: "不限" })
      }
      data.value = [...val] as DataItem[]
    }
  }
})
</script>

<style lang="scss" scoped>
.dict-segmented {
  :deep(.el-segmented) {
    --el-segmented-item-selected-bg-color: #ffe6e6;
    --el-segmented-item-selected-color: var(--el-color-primary);
    --el-segmented-bg-color: #f5f7fa;
    --el-segmented-color: #222;
    --el-segmented-padding: 0;
    --el-border-radius-base: 6px;
  }
}
</style>
